import storage from './storage.js'
import request from '@/utils/http.js';
// 检查登录
export function checkLogin() {
	const token = storage.get('user')
	if (!token) {
		uni.showModal({
			content: '需要登录',
			success(res) {
				if (res.confirm) {
					uni.navigateTo({
						url: '/pages/login/login'
					})
				}
			},

		})
	} else {
		return true
	}
}


import JSEncrypt from 'jsencrypt'
const encryptor = new JSEncrypt()
const publicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAquh02y4t1f62dtQ8Mv/XNl87/KHGMBHu9E4GcFXgeHOYKLLsHnsHDvIuSiz4j7GBQ9T5WSQXVSVXUT2I+W/qSi/3m5Gr0chqDBf5yeoHQ97KikznbMYS1mmX6GvDvCiEknVIdp2x8zmPNLYtg1b8qIv2NwV+ecoP3eglpCxE79IesacqKLKBIIqnlP39DNLiHF7VjzgvRIrv/pMyhMYFPtgQwGewKdTdesBKVY719XuaABVyYkcuT+45oPLlIwENjo3NO7IQiMyEReC/NDj8wJCbQ0wrHqgG02Sp/WEgBD6ngg4CWFRNK2wOC8DSxq3ne4zlfi5H14e6jIEEfLszzwIDAQAB'
encryptor.setPublicKey(`-----BEGIN PUBLIC KEY-----\n${publicKey}\n-----END PUBLIC KEY-----`);
/**
 * RSA 加密
 * @param {string} data - 需要加密的数据
 * @returns {string} 加密后的数据
 */
export function rsaEncrypt(data) {
  if (!data) return ''
  return encryptor.encrypt(data)
}



// 上传
import {
	getUplaodToken
} from '../api/common.js'
export async function uplaod(file, name, size = 1048576, type, callback) {

	let newFileName = new Date().getTime() + '_' + type + '_' + name
	console.log(newFileName, '文件名')
	console.log(file, '文件')
	uni.showLoading({
		title: '上传中'
	})


	// if (file.size > size) {
	// 	return
	// }

	try {
		const res = await getUplaodToken({
			type: type
		})
		if (!res.status) {
			const formData = {
				key: res.content.dir + '/' + newFileName, //上传文件名称
				policy: res.content.policy, //表单域
				'x-oss-signature-version': "OSS4-HMAC-SHA256",
				'x-oss-credential': res.content.x_oss_credential, //指明派生密钥的参数集
				'x-oss-date': res.content.x_oss_date, //请求的时间
				'x-oss-signature': res.content.signature, //签名认证描述信息
				'x-oss-security-token': res.content.security_token, //安全令牌
				success_action_status: "200", //上传成功后响应状态码
			}
			console.log(res.content.host.replace(/^http:/, 'https:'))
			uni.uploadFile({
				url: res.content.host.replace(/^http:/, 'https:'),
				filePath: file.path,
				name: 'file',
				file: file,
				formData: formData,
				success: (result) => {
					uni.hideLoading()
					console.log('上传响应:', res);
					if (result.statusCode === 200) {
						uni.showToast({
							title: '上传成功',
							icon: 'success'
						})
						console.info("上传成功完整地址", res.content.host.replace(/^http:/, 'https:') + '/' +
							res.content.dir + '/' + newFileName);
						const url = res.content.host.replace(/^http:/, 'https:') + '/' + res.content
							.dir + '/' + newFileName
						callback(url)
					}

				},
				fail: (err) => {
					console.error('请求接口失败:', err);
					uni.showToast({
						title: '上传失败',
						icon: 'error'
					})
				},
				error: (error) => {
					console.log(error)
					uni.hideLoading()
				}
			})
		}
	} catch (error) {
		//TODO handle the exception
		uni.hideLoading()
		console.log(error)
	}
}



// 获取地址
export function getLocate(callback) {
	// 检查位置授权
	uni.getSetting({
		success: (res) => {
			// 如果没有位置权限，请求授权
			if (!res.authSetting['scope.userLocation']) {
				uni.authorize({
					scope: 'scope.userLocation',
					success: () => {
						console.log('位置权限已授权');

					},
					fail: () => {
						console.log('位置权限未授权，将无法使用地图功能');
						// 可以引导用户去设置页开启权限
						uni.showModal({
							title: '权限提示',
							content: '需要获取你的位置权限才能使用地图选点功能',
							confirmText: '去设置',
							success: (modalRes) => {
								if (modalRes.confirm) {
									uni.openSetting();
								}
							}
						});
					}
				});
			}
		}
	});
	uni.chooseAddress({
		success(res) {
			console.log('获取地址成功', res)
			uni.showToast({
				title: '获取地址成功',
				icon: 'success'
			})
		},
		complete: (res,err) => {
				
			if(res.errMsg === "chooseAddress:ok"){
				return callback(res)
			}else{
				return callback(false)
			}
		},
		fail(err) {
			console.log(err)
			return false
			uni.showToast({
				title: '获取地址失败',
				icon: 'error'
			})
		}
	})


}

// 获取经纬度
export function getLocation(callback) {

	uni.getLocation({
		type: 'gcj02',
		success: (res) => {
			console.log('获取位置成功', res);
			 callback(res)
		},
		fail: (err) => {
			return false
			console.error('获取位置失败', err);
			uni.showToast({
				title: '定位失败，请授权位置信息',
				icon: 'none',
				duration: 3000
			});
		},
		complete: () => {
			uni.hideLoading();
		}
	});
}


// 格式地址
export function splitAddress(address) {
    // 定义省市区的结束标志
    const provinceEnd = ['省', '自治区'];
    const cityEnd = ['市', '自治州'];
    const districtEnd = ['区', '县', '市辖区', '县级市'];

    let province = '', city = '', district = '', detail = '';

    // 找到省
    for (let i = 0; i < address.length; i++) {
        if (provinceEnd.includes(address[i])) {
            province = address.substring(0, i + 1);
            address = address.substring(i + 1);
            break;
        }
    }

    // 找到市
    for (let i = 0; i < address.length; i++) {
        if (cityEnd.includes(address[i])) {
            city = address.substring(0, i + 1);
            address = address.substring(i + 1);
            break;
        }
    }

    // 找到区或县
    for (let i = 0; i < address.length; i++) {
        if (districtEnd.includes(address[i])) {
            district = address.substring(0, i + 1);
            detail = address.substring(i + 1);
            break;
        }
    }

    // 如果没有找到区或县，那么剩下的就是详细地址
    if (!district) {
        detail = address;
    }

    return {
        province: province.trim(),
        city: city.trim(),
        district: district.trim(),
        detail: detail.trim()
    };
}

